浏览器访问ip加8050端口,页面出现说明成功
splash使用:
使用lua脚本,需要一个main函数
简单实现:
- function main(splash)
- splash:go("http://www.baidu.com")
- splash:wait(0.5)
- return {c=splash:get_cookies()}
- end
获得百度页面的cookies,有些网站会在页面用js生成各种cookie用来加大爬虫难度
python调用方法:
- # -*-coding:utf-8 -*-
- __author__ = "ayou"
-
- import requests
- import json
-
- s = requests.session()
- #execute是执行脚本
- #脚本为lu,也可以使用js脚本
- url="http://192.168.99.100:8050/execute?lua_source="
- #以下脚本为访问百度,并返回cookies
- script = '''''
- function main(splash)
- splash:go("http://www.baidu.com")
- splash:wait(0.5)
- return {c=splash:get_cookies()}
- end
- '''
- cc={}
- r = s.get(url+script)
- a = str(r.content, encoding = "utf-8")
- jsondata = json.loads(a)
- for line in jsondata["c"]:
- cc[line["name"]]= line["value"]
- print(cc)
splash的execute是用来执行lua脚本,返回一段json,里面就是百度cookies
通过代理ip访问:
- # -*-coding:utf-8 -*-
- __author__ = "ayou"
-
- import requests
-
- s = requests.session()
- #execute是执行脚本
- #脚本为lu,也可以使用js脚本
- url="http://192.168.99.100:8050/execute?lua_source="
- #以下代码是通过代理ip访问
- script_1='''''
- function main(splash)
- splash:on_request(function(request)
- request:set_proxy{
- host = "60.21.132.218",
- port = 63000,
- }
- end)
- assert(splash:go("http://1212.ip138.com/ic.asp"))
- return splash:html()
- end
- '''
- r = s.get(url+script_1)
- a = str(r.content, encoding = "utf-8")
- print(a)
结果:

这是西刺上的一个免费代理ip
Splash支持lua脚本和js脚本,还支持在线脚本测试,并附带简单的函数提示说明

关闭splash :
先用 docker ps 命令找出splash的CONTAINER ID
然后用 docker stop 7b1f1412e7dc(CONTAINER ID) 命令关闭
Splash作为服务可以提供给各种语言使用
Splash文档:
http://splash.readthedocs.io/en/latest/install.html
Splash文档(英文)很完整,用法很丰富,仔细看会有很多惊喜
因为只用了一天Splash,还没法用它和
selenium+PhantomJS比较哪个方式更稳定快速,不过目前觉得它是一个神器,貌似用得人挺少,可惜
对splash进行了压力测试:
使用了siege
系统为macos sierra 10.12.3
测试命令:
siege -c 200 -r 5 http://192.168.99.100:8050/execute?lua_source=function+main%28splash%29%0D%0A++++splash%3Ago%28%22http%3A%2F%2Fwww.baidu.com%22%29%0D%0A++++splash%3Await%280.5%29%0D%0A++++return+%7Bc%3Dsplash%3Aget_cookies%28%29%7D%0D%0Aend
结果:

添加 nginx,参考:
flask笔记:11:gunicorn+gevent+nginx+flask部署,使用siege进行服务器压力测试
打开nginx.conf 修改:
location @pp {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
#修改成splash地址
proxy_pass http://192.168.99.100:8050;
}
重启nginx:sudo /usr/local/nginx/sbin/nginx -s reload
测试命令:
siege -c 200 -r 5 http://127.0.0.1:8088/execute?lua_source=function+main%28splash%29%0D%0A++++splash%3Ago%28%22http%3A%2F%2Fwww.baidu.com%22%29%0D%0A++++splash%3Await%280.5%29%0D%0A++++return+%7Bc%3Dsplash%3Aget_cookies%28%29%7D%0D%0Aend
结果:

公司用
selenium+PhantomJS处理一些复杂网站封装成服务,但是不太稳定,
PhantomJS好像释放内存有问题,爆过几次服务器内存,从上面的结果和我这两天用Splash的感受觉得Splash比
selenium+PhantomJS的模式更适合做成服务式的爬虫服务
关于siege请参看:
flask笔记:11:gunicorn+gevent+nginx+flask部署,使用siege进行服务器压力测试